package com.lizemin.monitor.client.aop;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ApiMonitoringAspect {

    private final MeterRegistry meterRegistry;

    public ApiMonitoringAspect(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    /**
     * 统计接口调用次数
     *
     * @param joinPoint 切入点
     */
    @Before("execution(* com.lizemin.monitor.client.controller.*.*(..))")
    public void countApiCalls(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            // 获取接口的请求路径
            HttpServletRequest request = attributes.getRequest();
            String apiPath = request.getRequestURI();

            // 创建或获取计数器
            // tags用来区分不同的接口，实现统计每个接口的调用次数
            Counter counter = meterRegistry.counter("api.calls", "path", apiPath);
            counter.increment();
        }
    }
}